package com.ocom.webapi.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.excel.EasyExcelUtil;
import com.ocom.common.vo.payconfig.cloudcomputing.CloudComputingVo;
import com.ocom.common.vo.webapi.CloudComputingPageVo;
import com.ocom.common.vo.webapi.SchoolWifiPageVo;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.HumanClientService;
import com.ocom.webapi.feign.PayConfigClientService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@RestController
@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
public class CloudComputingPageController {

    @Autowired
    private PayConfigClientService payConfigClientService;

    @Autowired
    private HumanClientService humanClientService;

    @PostMapping(value = WebApiServiceUrl.Url_CloudComputingPageOnShow)
    public Result cloudComputingPageOnShow(@RequestBody CloudComputingVo cloudComputingVo) {

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        Long comId = yoCiUser.getComId();
        if (ObjectUtil.isEmpty(cloudComputingVo.getComId())) {
            cloudComputingVo.setComId(Math.toIntExact(comId));
        }
        return payConfigClientService.getCloudComputingList(cloudComputingVo);
    }

    @PostMapping(value = WebApiServiceUrl.Url_CloudComputingPageModify)
    public Result cloudComputingPageModify(@RequestBody CloudComputingVo cloudComputingVo) {
        log.info("修改云电脑:{}", cloudComputingVo.toString());
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        Long comId = yoCiUser.getComId();
        String username = yoCiUser.getUsername();
        if (ObjectUtil.isEmpty(cloudComputingVo.getComId())) {
            cloudComputingVo.setComId(Math.toIntExact(comId));
        }
        if (ObjectUtil.isNotEmpty(username)) {
            cloudComputingVo.setUpdateUser(username);
        }
        return payConfigClientService.updateCloudComputingInfo(cloudComputingVo);

    }


    @PostMapping(value = WebApiServiceUrl.Url_CloudComputingPageCheckStatus)
    public Result cloudComputingPageCheckStatus(@RequestBody CloudComputingVo cloudComputingVo) {
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        Long comId = yoCiUser.getComId();
        String username = yoCiUser.getUsername();
        if (ObjectUtil.isEmpty(cloudComputingVo.getComId())) {
            cloudComputingVo.setComId(Math.toIntExact(comId));
        }
        if (ObjectUtil.isNotEmpty(username)) {
            cloudComputingVo.setUpdateUser(username);
        }
        return payConfigClientService.updateCloudComputingInfo(cloudComputingVo);
    }


    @PostMapping(value = WebApiServiceUrl.Url_CloudComputingPageImport)
    public Result cloudComputingPageImport(@RequestParam Long comId, @RequestPart("file") MultipartFile file) throws IOException, InvalidFormatException {

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
//        Long comId = yoCiUser.getComId();
        String username = yoCiUser.getUsername();

        List<CloudComputingPageVo> computingPageVos = EasyExcelUtil.readFromExcel(file.getInputStream(), CloudComputingPageVo.class, 0);

        Map<String, Integer> statusMap = new HashMap<>();
        List<CloudComputingVo> list = computingPageVos.stream().filter(Objects::nonNull).map(cloudComputingVo -> {
            CloudComputingVo cloudComputing = new CloudComputingVo();
            BeanUtils.copyProperties(cloudComputingVo,cloudComputing );
            statusMap.put("待审核", 0);
            statusMap.put("通过", 1);
            statusMap.put("不通过", 2);
            cloudComputing.setStatus(statusMap.getOrDefault(cloudComputingVo.getStatus(), 0));
            return cloudComputing;
        }).collect(Collectors.toList());


        Map<String, Object> map = new HashMap<>();
        AtomicInteger count = new AtomicInteger();
        list.forEach(cloudComputingVo -> {
            String pName = cloudComputingVo.getPName();
            String pCode = cloudComputingVo.getPCode();
            map.put("pName", pName);
            map.put("pCode", pCode);
            map.put("page",0);
            map.put("size",0);
            map.put("comId",comId);
            Result personInfo = humanClientService.PersonnelGetPersonInfo(map);

            JSONObject jsonObject =JSONObject.parseObject(JSON.toJSONString(personInfo.getData()));
            if(jsonObject.getInteger("total")==0||ObjectUtil.isEmpty(jsonObject.get("list"))) {
                return;
            }

            JSONArray jsonArray = jsonObject.getJSONArray("list");

            if (ObjectUtil.isEmpty(jsonArray)) {
                    cloudComputingVo.setPId(Math.toIntExact(jsonObject.getLong("pId")));
                    cloudComputingVo.setComId(Math.toIntExact(comId));
                    cloudComputingVo.setUpdateUser(username == null ? cloudComputingVo.getUpdateUser() : username);
                    payConfigClientService.updateCloudComputingInfo(cloudComputingVo);
                    count.getAndIncrement();
            } else {
                jsonArray.forEach(json -> {
                        JSONObject object = (JSONObject) json;
                        cloudComputingVo.setPId(Math.toIntExact(object.getLong("pId")));
                        cloudComputingVo.setComId(Math.toIntExact(comId));
                        cloudComputingVo.setUpdateUser(username == null ? cloudComputingVo.getUpdateUser() : username);
                        payConfigClientService.updateCloudComputingInfo(cloudComputingVo);
                        count.getAndIncrement();
                });
            }
        });
        return ResultUtil.success("处理成功人数：" + count.get());
    }

    @GetMapping(WebApiServiceUrl.Url_ExportCloudComputing)
    public void exportCloudComputing(HttpServletResponse response,CloudComputingVo cloudComputingVo) {
        log.info("开始导出云电脑账号 请求参数：{}",cloudComputingVo);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置背景颜色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        //设置头字体
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short)13);
        headWriteFont.setBold(true);
        headWriteCellStyle.setWriteFont(headWriteFont);
        //设置头居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //内容策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        String fileName = null;
        try {
            fileName = URLEncoder.encode("云电脑账号", "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.setHeader("Content-disposition",  fileName + ".xlsx");

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        cloudComputingVo.setComId(Math.toIntExact(yoCiUser.getComId()));
        cloudComputingVo.setPage(0);
        cloudComputingVo.setSize(0);
        Result result = payConfigClientService.getCloudComputingList(cloudComputingVo);
        ArrayList<CloudComputingPageVo> arrayList = new ArrayList<>();
        Map<Integer, String> statusMap = new HashMap<>();
        statusMap.put(0, "待审核");
        statusMap.put(1, "通过");
        statusMap.put(2, "不通过");
        if(result.getCode()==200){
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));
            if(ObjectUtil.isEmpty(jsonObject)){
                return;
            }
            JSONArray list = jsonObject.getJSONArray("list");
            if(ObjectUtil.isEmpty(list)){
                return;
            }
            list.forEach(obj->{
                CloudComputingVo cloudComputingVo1 = JSON.parseObject(JSON.toJSONString(obj), CloudComputingVo.class);
                CloudComputingPageVo cloudComputingPageVo = new CloudComputingPageVo();
                String status = statusMap.getOrDefault(cloudComputingVo1.getStatus(), "未知状态");
                cloudComputingPageVo.setStatus(status);
                cloudComputingPageVo.setBalance(cloudComputingVo1.getBalance());
                cloudComputingPageVo.setPassword(cloudComputingVo1.getPassword());
                cloudComputingPageVo.setRemark(cloudComputingVo1.getRemark());
                cloudComputingPageVo.setPCode(cloudComputingVo1.getPCode());
                cloudComputingPageVo.setUserName(cloudComputingVo1.getUserName());
                cloudComputingPageVo.setUseInfo(cloudComputingVo1.getUseInfo());
                cloudComputingPageVo.setPName(cloudComputingVo1.getPName());
                cloudComputingPageVo.setCustomerInfo(cloudComputingVo1.getCustomerInfo());
                cloudComputingPageVo.setEndTime(cloudComputingVo1.getEndTime());
                arrayList.add(cloudComputingPageVo);
            });
        }
        try {
            EasyExcel.write(response.getOutputStream(), CloudComputingPageVo.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("云电脑账号").doWrite(arrayList);
        } catch (IOException e) {
            log.error("导出云电脑账号失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }

    }
}




